package com.dominator.serviceImpl;

import com.dominFramework.core.dao.SqlDao;
import com.dominFramework.core.typewrap.Dto;
import com.dominFramework.core.typewrap.Dtos;
import com.dominFramework.core.utils.SystemUtils;
import com.dominator.enums.ReqEnums;
import com.dominator.mybatis.dao.T_accountPO;
import com.dominator.mybatis.dao.T_userPO;
import com.dominator.repository.DaoAccount;
import com.dominator.repository.DaoAccountTicket;
import com.dominator.repository.DaoUser;
import com.dominator.service.*;
import com.dominator.utils.api.ApiMessage;
import com.dominator.utils.api.ApiMessageUtil;
import com.dominator.utils.api.ApiUtils;
import com.dominator.utils.encode.Des3Utils;
import com.dominator.utils.encode.HzEncodeUtil;
import com.dominator.utils.exception.ApiException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
public class ApiLoginServiceImpl implements ApiLoginService {

    private static Logger log = LoggerFactory.getLogger(ApiLoginServiceImpl.class);

    @Autowired
    SqlDao sqlDao;

    @Autowired
    ApiSmsService apiSmsService;

    @Autowired
    ApiCommonService apiCommonService;

    @Autowired
    ApiUserService apiUserService;



    @Autowired
    DaoUser userDao;

    @Autowired
    DaoAccount accountDao;
    @Autowired
    DaoAccountTicket accountTicketDao;


    @Override
    public ApiMessage register(Dto dto) throws ApiException {
        ApiMessage msg = new ApiMessage();
        ApiUtils.checkParam(dto, "phoneNum,verifyCode,password");

        // 查询手机是否存在
        if (SystemUtils.isNotEmpty(userDao.selectByPhoneNum(dto.getString("phoneNum")))) {
            log.error("手机号已存在");
            throw new ApiException(ReqEnums.REQ_PHONE_EXSIT);
        }

        // 校验验证码是否存在
        dto.put("verifyType", 1);
        apiSmsService.verifySms(dto);
        // 查询邀请人信息
        T_userPO inviteUser = null;
        if (SystemUtils.isNotEmpty(dto.getString("invitePhoneNum"))) {
            inviteUser = userDao.selectByPhoneNum(dto.getString("invitePhoneNum"));
            if (SystemUtils.isNotEmpty(inviteUser)) {
                dto.put("pid", inviteUser.getId());
            } else {
                log.error("邀请人手机号不存在");
                throw new ApiException(ReqEnums.REQ_INVITE_PHONE_NOT_EXSIT);
            }
        }

        // 创建用户信息
        Integer res = userDao.createPhoneUser(dto);
        if (res == 1) {
            T_userPO userPO=userDao.selectByPhoneNum(dto.getString("phoneNum"));
            accountDao.createAccount(userPO);
            dto.put("merchantId","0eb7777388bc41abb2bc6d0f18e460a0");
            dto.put("points",new BigDecimal(20));
            try {
                apiCommonService.transferPointsToUser(dto);
            }catch (ApiException e){
                log.error("互融体验金发送失败："+e.getMessage());
            }
            return ApiMessageUtil.success();
        } else {
            throw new ApiException(ReqEnums.REQ_CREATE_USER_ERROR);
        }

    }

    @Override
    public ApiMessage picRegister(Dto dto) throws ApiException {
        ApiMessage msg = new ApiMessage();
        ApiUtils.checkParam(dto, "phoneNum,picVerifyCode,password,uuid");
        //验证图形验证码
        apiCommonService.verifyPicCode(dto);

        // 查询手机是否存在
        if (SystemUtils.isNotEmpty(userDao.selectByPhoneNum(dto.getString("phoneNum")))) {
            log.error("手机号已存在");
            throw new ApiException(ReqEnums.REQ_PHONE_EXSIT);
        }


        // 创建用户信息
        Integer res = userDao.createPhoneUser(dto);
        if (res == 1) {
            return ApiMessageUtil.success();
        } else {
            throw new ApiException(ReqEnums.REQ_CREATE_USER_ERROR);
        }


    }

    @Override
    public ApiMessage phonePasswordLogin(Dto dto) throws ApiException {
        ApiUtils.checkParam(dto, "phoneNum,password");
        T_userPO user = userDao.selectByPhoneNum(dto.getString("phoneNum"));
        if (SystemUtils.isEmpty(user)) {
            log.error("用户不存在");
            throw new ApiException(ReqEnums.REQ_USER_NOT_EXSIT);
        } else if (!user.getPassword().equals(Des3Utils.encode(dto.getString("password")))) {
            log.error("密码错误");
            throw new ApiException(ReqEnums.REQ_WRONG_PASSWORD);
        }
        // 登录成功后处理
        dto.put("user", user);
        return loginSuccess(dto);
    }

    @Override
    public ApiMessage phoneVerifyLogin(Dto dto) throws ApiException {
        ApiUtils.checkParam(dto, "phoneNum,verifyCode");
        // 校验验证码是否存在
        dto.put("verifyType", 2);
        apiSmsService.verifySms(dto);
        T_userPO user = userDao.selectByPhoneNum(dto.getString("phoneNum"));
        if (SystemUtils.isEmpty(user)) {
            // 创建用户信息
            Integer res = userDao.createPhoneUser(dto);
            if (res == 1) {
                // 登录成功后处理
                user = userDao.selectByPhoneNum(dto.getString("phoneNum"));
                dto.put("user", user);
                return loginSuccess(dto);
            } else {
                throw new ApiException(ReqEnums.REQ_CREATE_USER_ERROR);
            }
        }
        // 登录成功后处理
        dto.put("user", user);
        return loginSuccess(dto);

    }

    @Override
    public ApiMessage wxOpenIdLogin(Dto dto) throws ApiException {
        ApiUtils.checkParam(dto, "wxOpenId");
        T_userPO user = userDao.selectByWxOpenId(dto.getString("wxOpenId"));
        if (SystemUtils.isEmpty(user)) {
            log.error("用户不存在");
            throw new ApiException(ReqEnums.REQ_USER_NOT_EXSIT);
        }
        // 登录成功后处理
        dto.put("user", user);
        return loginSuccess(dto);

    }

    @Override
    public ApiMessage qqLogin(Dto dto) throws ApiException {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public ApiMessage weixinLogin(Dto dto) throws ApiException {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public ApiMessage weiboLogin(Dto dto) throws ApiException {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public ApiMessage hzLogin(Dto dto) throws ApiException {
        ApiUtils.checkParam(dto, "unionId");
        String decode=HzEncodeUtil.getDecryptString(dto.getString("unionId"));
        String phoneNum=decode.split("_")[0];
        String fenful=decode.split("_")[1];
        if (!"fenful".equals(fenful)){
            log.error("签名错误");
            throw new ApiException(ReqEnums.UNION_LOGIN_ERROR);
        }
        if (ApiUtils.isMobile(phoneNum)){

            T_userPO user = userDao.selectByPhoneNum(phoneNum);
            if (SystemUtils.isEmpty(user)) {
                // 创建用户信息
                dto.put("phoneNum", phoneNum);
                Integer res = userDao.createPhoneUser(dto);
                if (res == 1) {
                    // 登录成功后处理
                    user = userDao.selectByPhoneNum(phoneNum);
                    try {
                        dto.put("merchantId","78e831df4de645bfa709920337a05d60");
                        dto.put("points",new BigDecimal(20));
                        dto.put("phoneNum",phoneNum);
                        apiCommonService.transferPointsToUser(dto);
                    }catch (ApiException e){
                        log.error("赠送积分失败："+e.getMessage());
                    }
                    dto.put("user", user);
                    dto.put("otherFirst","1");
                } else {
                    throw new ApiException(ReqEnums.REQ_CREATE_USER_ERROR);
                }
            }
            dto.put("user", user);

        }else {
            log.error("手机号不合法");
            throw new ApiException(ReqEnums.REQ_CREATE_USER_ERROR);
        }
        return loginSuccess(dto);
    }


    public ApiMessage loginSuccess(Dto dto) throws ApiException {
        T_userPO user = (T_userPO) dto.get("user");
        if ("0".equals(user.getIs_valid())) {
            log.error("用户已被停用，请联系客服");
            throw new ApiException(ReqEnums.REQ_USER_IS_NOT_VALID);
        }
        // 记录登录日志
        user.setIp(dto.getString("ip"));
        user.setDevice_num(dto.getString("deviceNum"));
        user.setModify_time(new Date());
        user.setLast_login_time(new Date());
        userDao.updateByPrimaryKey(user);

        // 获取token值
        String token = ApiUtils.getTokenByUserPO(user);
        // 查询账户 如果没有账户给添加一个
        T_accountPO account = accountDao.selectByUserId(user.getId());
        if (SystemUtils.isEmpty(account)) {
            accountDao.createAccount(user);
            account = accountDao.selectByUserId(user.getId());
        }
        Dto outDto = Dtos.newDto();
        outDto.put("token", token);
        outDto.put("phoneNum", SystemUtils.isEmpty(user.getPhone_num()) ? "" : user.getPhone_num());
        outDto.put("nickName", SystemUtils.isEmpty(user.getNick_name()) ? "" : user.getNick_name());
        outDto.put("headImg", SystemUtils.isEmpty(user.getHead_img()) ? "" : user.getHead_img());
        outDto.put("genter", SystemUtils.isEmpty(user.getGenter()) ? "" : user.getGenter());
        outDto.put("id", SystemUtils.isEmpty(user.getId()) ? "" : user.getId());
        outDto.put("points", SystemUtils.isEmpty(account.getPoints()) ? 0 : account.getPoints());
        outDto.put("birthday", SystemUtils.isEmpty(user.getBirthday()) ? "" : user.getBirthday());
        outDto.put("email", SystemUtils.isEmpty(user.getEmail()) ? "" : user.getEmail());
        //第三方首次登录给个标志 otherFirst
        outDto.put("otherFirst",SystemUtils.isEmpty(dto.getString("otherFirst"))?"0":dto.getString("otherFirst"));

        //outDto.put("wxOpenId",SystemUtils.isEmpty(dto.getString("wxOpenId")) ? "" : dto.getString("wxOpenId"));
        try{
            if(SystemUtils.isEmpty(user.getWx_open_id())&&SystemUtils.isNotEmpty(dto.getString("wxOpenId"))){
                log.info("=======绑定微信=======/"+dto.getString("wxOpenId"));
                apiUserService.bindingWxOpenId(dto);
            }
        }catch (ApiException e){
            log.info("==========错误"+e.getMessage());
        }

        //outDto.put("money", SystemUtils.isEmpty(account.getPoints()) ? 0 : account.getMoney());
        // 用户推荐人手机号
//        if (SystemUtils.isNotEmpty(user.getPid())) {
//            T_userPO inviteUser = userDao.selectByPrimaryKey(user.getPid());
//            if (SystemUtils.isNotEmpty(inviteUser)) {
//                outDto.put("invitePhoneNum", inviteUser.getPhone_num());
//            }
//        } else {
//            outDto.put("invitePhoneNum", "");
//        }
        // 用户邀请的人数
       // outDto.put("inviteNum", userDao.countInvitePerson(user.getId()));

        return ApiMessageUtil.success(outDto);
    }

}
